/**
 * 
 */
package com.owen.he.jee.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.owen.he.jee.model.Jjyjdr;
import com.owen.he.jee.service.IndexService;
import com.owen.he.jee.utils.ExcelRelation;
import com.owen.he.jee.utils.excel.ExcelColumnPojo;
import com.owen.he.jee.utils.excel.ExcelFileUtils;
import com.owen.he.jee.utils.excel.ExportingExcel;
import com.owen.he.jee.utils.excel.YjdrMapUtils;
import com.owen.he.jee.web.excel.ExcelView;

/**
 * 基金业绩导入管理
 * @author chenly 
 *
 * @version createtime:2016-10-13 上午10:46:05 
 */
@Controller
@RequestMapping("module")
public class YjdrController {
	private String[] columns = {};
	
	@Autowired
	IndexService indexService;
	
	/**
	 * 新版导出
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/exportTemplateNew", method = RequestMethod.GET)
	public ModelAndView exportTemplateNew(ModelMap model,HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv = new ModelAndView();
		String skey = request.getParameter("key");
		skey = "jjyjdr";
		List<ExcelColumnPojo> lists = new ArrayList<ExcelColumnPojo>();
		ExportingExcel excel = null;
		String msg = "";
		try{
			String key = (skey!=null)? skey.trim() : "";
			//实例化导出标题头
			excel = initExportYjdrExcelTemplate(skey, Jjyjdr.class);
		}catch(Exception e){
			msg = "程序出错";
		}
		request.setAttribute("error", msg);
		ExcelView viewExcel = new ExcelView();
		model.put("obj", excel);
	    return new ModelAndView(viewExcel, model);   
	}
	
	@RequestMapping(value = "/exportResultNew", method =  {RequestMethod.POST,RequestMethod.GET})
	public ExportingExcel exportResultNew(HttpServletRequest request,HttpServletResponse response) {
		ExportingExcel excel = null;
		String msg = "";
		String skey = request.getParameter("key");
		skey = "jjyjdr";
		//获取要导出的数据库字段字段，作为sql的一部分
		String columnsSql = getExportYjdrColumns(Jjyjdr.class);
		List<Map> list = indexService.resultData(skey ,columnsSql);
		List<Map> resultList = new ArrayList<>();
		try{
			String key = (skey!=null)? skey.trim() : "";
			excel = initExportYjdrExcelTemplate(skey, Jjyjdr.class);
			//设置数据key-index  value - data
			setExportYjdrExcelData(Jjyjdr.class, list, resultList);
			excel.setExcelData(resultList);
		}catch(Exception e){
			msg = "程序出错";
		}
		request.setAttribute("error", msg);
		return excel;
	}

	private String getExportYjdrColumns(Class<Jjyjdr> jjyjdr) {
		return ExcelFileUtils.readAnnoExportField(jjyjdr);
	}

	/**
	 * 设置数据
	 * @param jjyjdr
	 * @param list
	 * @param resultList
	 */
	private void setExportYjdrExcelData(Class<Jjyjdr> jjyjdr, List<Map> list,
			List<Map> resultList) {
		List<ExcelRelation> excelRelations = ExcelFileUtils.readAnnoExportTitleNameField(jjyjdr);
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			Map<String,Object> dataMap = (Map<String, Object>) iter.next();
			Map map = new HashMap<>();
			for (ExcelRelation temp : excelRelations) {
				String field = temp.getField();
				Integer index = temp.getIndex();
				Object value = dataMap.get(field);
				map.put(index, value);
			}
			resultList.add(map);
		}
	}

	/**
	 * 解析为取得头部标题
	 * @param jjyjdr
	 * @return
	 */
	private ExportingExcel initExportYjdrExcelTemplate(String key, Class<Jjyjdr> jjyjdr) {
		List<ExcelRelation> excelRelations = ExcelFileUtils.readAnnoExportTitleNameField(jjyjdr);
		ExportingExcel excel = new ExportingExcel();
		List<ExcelColumnPojo> lists = new ArrayList<ExcelColumnPojo>();
		excel.setFileName(key);
		for(ExcelRelation r:excelRelations){
			ExcelColumnPojo obj = new ExcelColumnPojo();
			obj.setName(r.getName());
			obj.setText(r.getName());
			obj.setIndex(r.getIndex());
			obj.setReq("Y");
			lists.add(obj);
		}
		excel.setType(1);
		excel.setHeaderColList(lists);
		return excel;
	}



	/***********************************原版**********************************************/
	@RequestMapping(value = "/exportTemplate", method = RequestMethod.GET)
	public ModelAndView exportTemplate(ModelMap model,HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv = new ModelAndView();
		String skey = request.getParameter("key");
		List<ExcelColumnPojo> lists = new ArrayList<ExcelColumnPojo>();
		ExportingExcel excel = null;
		String msg = "";
		try{
			//String key = (request.getParameter("key")!=null)? request.getParameter("key").trim() : "";
			String key = (skey!=null)? skey.trim() : "";
			excel = initExcelTemplate(key);
		}catch(Exception e){
			msg = "程序出错";
		}
		request.setAttribute("error", msg);
		ExcelView viewExcel = new ExcelView();
		model.put("obj", excel);
	    return new ModelAndView(viewExcel, model);   
	}
	
	
	@RequestMapping(value = "/exportResult/{key}", method =  {RequestMethod.POST,RequestMethod.GET})
	public ExportingExcel exportResult(HttpServletRequest request,HttpServletResponse response,
			@PathVariable("key")  String skey){
		ExportingExcel excel = null;
		String msg = "";
		List<Map> list = new ArrayList<Map>();
		List<Map> resultList = new ArrayList<Map>();
		try{
			//String key = (request.getParameter("key")!=null)? request.getParameter("key").trim() : "";
			String key = (skey!=null)? skey.trim() : "";
			excel = initExcelTemplate(key);
			String path = request.getContextPath();
			
			String isOk = request.getParameter("isOk");
			
			Map<String,String> columnMap =new HashMap<String,String>();
			columnMap = getColumnMap(key);
			//数据转到表格数据列表
			for(int i=0;i<list.size();i++){
				Map map = list.get(i);
				Map m = new HashMap();
				buildMap(columnMap,map,m);
				resultList.add(m);
			}
			
			excel.setExcelData(resultList);
		}catch(Exception e){
			msg = "程序出错";
		}
		request.setAttribute("error", msg);
		return excel;
	}
	/**
	 * 初始化表头
	 * @param key
	 * @return
	 */
	private ExportingExcel initExcelTemplate(String key){
		ExportingExcel excel = new ExportingExcel();
		List<ExcelColumnPojo> lists = new ArrayList<ExcelColumnPojo>();
		excel.setFileName(YjdrMapUtils.map.get(key));
		if(!StringUtils.isEmpty(key)){
			int i= 0;
			for(String s:YjdrMapUtils.headMap.get(key)){
				ExcelColumnPojo obj = new ExcelColumnPojo();
				
				obj.setName(s.split("_")[2]);
				obj.setText(s.split("_")[2]);
				obj.setIndex(i);
				if(i>=0 && i<=4){
					obj.setReq("Y");
				}
				i++;
				lists.add(obj);
			}
			excel.setType(1);
			excel.setHeaderColList(lists);
		}
		return excel;
	}
	/**
	 * 获了表头列的排序表
	 * @param key
	 * @return
	 */
	private Map<String,String> getColumnMap(String key){
		Map<String,String> columnMap = new HashMap<String,String>();
		
		for(String s:columns){
			columnMap.put(s.split("_")[1], s.split("_")[0]);
			
		}
		return columnMap;
	}
	/**
	 * 按表头列的排序赋值
	 * @param columnMap
	 * @param row
	 * @param map
	 */
	private void buildMap(Map<String,String> columnMap,Map row,Map map){
		
		Iterator<Map.Entry<String, String>> it = columnMap.entrySet().iterator();
		int i = 0;
		while(it.hasNext()){
			Map.Entry<String, String> entry = it.next();
			System.out.println(entry.getKey());
			map.put(entry.getValue(), value(row,entry.getKey()));
			i++;
		}
	}
	
	private String value(Map map,String key){
		String value = "";
		if(null!=map.get(key.toUpperCase())){
			value = (String) map.get(key.toUpperCase().toString());
		}
		return value;
	}
	
	public static void main(String[] args){
		Map map=new HashMap();
		map.put(0, "111");
		System.out.println(map.get(0));
		Gson g = new Gson();
		String str = "{\"19\":\"_19\",\"22\":\"_22\",\"17\":\"_17\",\"18\":\"_18\",\"15\":\"_15\",\"16\":\"_16\",\"13\":\"_13\",\"14\":\"_14\",\"11\":\"_11\",\"12\":\"_12\",\"3\":\"246_3\",\"21\":\"_21\",\"2\":\"20160313_2\",\"20\":\"_20\",\"10\":\"_10\",\"1\":\"_1\",\"0\":\"14011576507011_0\",\"7\":\"_7\",\"6\":\"10.24_6\",\"5\":\"277_5\",\"4\":\"89.76_4\",\"9\":\"_9\",\"8\":\"_8\"}";

		int i = 0;
		Map map2 = g.fromJson(str, Map.class);
		System.out.println(g.toJson(map2));
		System.out.println(map2.get(i+""));
	}
}
